/**
 */
package com.dingpeikeji.quickdeer.core.modules.schedef.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;



import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.common.persistence.Page;
import com.dingpeikeji.quickdeer.core.common.utils.DateUtils;
import com.dingpeikeji.quickdeer.core.common.utils.StringUtils;
import com.dingpeikeji.quickdeer.core.common.web.BaseController;
import com.dingpeikeji.quickdeer.core.modules.bus.entity.TCompBus;
import com.dingpeikeji.quickdeer.core.modules.bus.service.TCompBusService;
import com.dingpeikeji.quickdeer.core.modules.schedef.entity.TSchedef;
import com.dingpeikeji.quickdeer.core.modules.schedef.service.TSchedefService;
import com.dingpeikeji.quickdeer.core.modules.site.entity.TSitedtl;
import com.dingpeikeji.quickdeer.core.modules.site.service.TSitedtlService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.Office;
import com.dingpeikeji.quickdeer.core.modules.sys.service.OfficeService;
import com.dingpeikeji.quickdeer.core.modules.sys.utils.UserUtils;
import com.dingpeikeji.quickdeer.core.modules.viewspot.entity.SysViewspot;
import com.dingpeikeji.quickdeer.core.modules.viewspot.service.SysViewspotService;


/**
 * 班次定义Controller
 * 
 * @author Zhaoy
 * @version 2016-05-27
 */
@Controller
@RequestMapping(value = "${adminPath}/schedef/tSchedef")
public class TSchedefController extends BaseController {

	@Autowired
	private TSchedefService tSchedefService;
	@Autowired
	private TSitedtlService tSitedtlservice;
	@Autowired
	private TCompBusService compBusService;
	@Autowired
	private OfficeService officeService;
	@Autowired
	private SysViewspotService sysViewspotService;

	@ModelAttribute
	public TSchedef get(@RequestParam(required = false) String id) {
		if (StringUtils.isNotBlank(id)) {
			return tSchedefService.get(id);
		} else {
			return new TSchedef();
		}
	}
	
	@RequiresPermissions("schedef:tSchedef:view")
	@RequestMapping(value = "modifylist")
	public String modifylist(TSchedef tSchedef, HttpServletRequest request, HttpServletResponse response, Model model) {
		if (tSchedef.getOfficeid() == null)
			tSchedef.setOfficeid(UserUtils.getUser().getOffice().getId());
		
		//只查询原始记录
		tSchedef.setDefType(TSchedef.DEF_ORIGIN);
		
		// 只能读取已经审核通过的班次信息
		tSchedef.setAuditstatus("1");
		Page<TSchedef> page = tSchedefService.findPage(new Page<TSchedef>(request, response), tSchedef);
		model.addAttribute("page", page);
		return "modules/schedef/tSchedefModifyList";

	}
	
	@RequiresPermissions("schedef:tSchedef:view")
	@RequestMapping(value = { "list", "" })
	public String list(TSchedef tSchedef, HttpServletRequest request, HttpServletResponse response, Model model) {
		//只查询原始记录
		tSchedef.setDefType(TSchedef.DEF_ORIGIN);
		
		Page<TSchedef> page = tSchedefService.findPage(new Page<TSchedef>(request, response), tSchedef);
		model.addAttribute("page", page);
		return "modules/schedef/tSchedefList";

	}
	
	@RequiresPermissions("schedef:tSchedef:view")
	@RequestMapping(value = "dispatchlist")
	public String dispatchlist(TSchedef tSchedef, HttpServletRequest request, HttpServletResponse response, Model model) {
		//只查询调度记录
		TSchedef query = new TSchedef();		
		
		query.setDefType(TSchedef.DEF_DISPATCH);
		query.setOriScheid(tSchedef.getScheid());
				
		Page<TSchedef> page = tSchedefService.findPage(new Page<TSchedef>(request, response), query);
		model.addAttribute("page", page);
		return "modules/schedef/tDefDispatchList";

	}

	// 通过车牌号 查询汽车信息
	@RequestMapping(value = "ajaxList")
	@ResponseBody
	public List<TCompBus> ajaxList(HttpServletRequest request, HttpServletResponse response, Model model) {
		// 通过officeid 查询客运公司巴士信息 AJAX
		String busid = request.getParameter("busid");
		TCompBus retBus = compBusService.get(busid);
		List<TCompBus> retBuslist = new ArrayList<TCompBus>();
		retBuslist.add(retBus);
		return retBuslist;
	}
	
	// 通过传入的城市信息查询客运公司
	@RequestMapping(value = "getOfficeByCitys")
	@ResponseBody
	public List<Office> getOfficeByCitys(HttpServletRequest request, HttpServletResponse response, Model model) {
		// 通过citys 查询客运公司巴士信息 AJAX
		String citys = request.getParameter("citys");
		List<Office> officelist = officeService.getOfficeByCitys(citys);
		
		return officelist;
	}

	// 通过客运公司查询当前公司下所有的车牌号
	@RequestMapping(value = "ajaxVehiclename")
	@ResponseBody
	public List<TCompBus> ajaxVehiclename(HttpServletRequest request, HttpServletResponse response, Model model) {
		// 通过officeid 查询客运公司巴士信息 AJAX
		String officeids = request.getParameter("officeids");
		return compBusService.findListOffice(officeids);
	}

	// 通过城市查询城市与景点
	@RequestMapping(value = "ajaxStied")
	@ResponseBody
	public List<TSitedtl> ajaxStied(HttpServletRequest request, HttpServletResponse response, Model model) {
		// 通过城市编号 查询对应的景点
		String code = request.getParameter("code");
		if (code != null) {
			TSitedtl sitedtl = new TSitedtl();
			sitedtl.setCitycode(code);
			String[] strArray={"0","2"};
			sitedtl.setSpottypes(strArray);
			System.out.println("查询出来的上下客点信息============" + tSitedtlservice.findList(sitedtl));
			return tSitedtlservice.findList(sitedtl);
		}
		return null;
	}

	// 通过城市查询上下客点
	@RequestMapping(value = "ajaxBoard")
	@ResponseBody
	public List<TSitedtl> ajaxBoard(HttpServletRequest request, HttpServletResponse response, Model model) {
		// 通过城市编号 查询对应的景点
		String code = request.getParameter("code");
		if (code != null) {
			TSitedtl sitedtl = new TSitedtl();
			sitedtl.setCitycode(code);
			String[] strArray={"1","3","4","5","6","7","8","9"};
			sitedtl.setSpottypes(strArray);
			System.out.println("查询出来的上下客点信息============" + tSitedtlservice.findList(sitedtl));
			return tSitedtlservice.findList(sitedtl);
		}
		return null;
	}
	// 通过城市查询景点
	@RequestMapping(value = "ajaxSpot")
	@ResponseBody
	public List<SysViewspot> ajaxSpot(HttpServletRequest request, HttpServletResponse response, Model model) {
		// 通过城市编号 查询对应的景点
		String code = request.getParameter("code");
		if (code != null) {
			SysViewspot viewspot = new SysViewspot();
			viewspot.setCitycode(code);
			System.out.println("查询出来的景点信息============" + sysViewspotService.findList(viewspot));
			return sysViewspotService.findList(viewspot);
		}
		return null;
	}

	@RequiresPermissions("schedef:tSchedef:view")
	@RequestMapping(value = "form")
	public String form(TSchedef tSchedef, String updateorview, Model model) {
		Date tomorrow = new Date();
		Calendar ca = new GregorianCalendar();
		ca.setTime(tomorrow);
		ca.add(Calendar.DATE, 1);
		tomorrow = ca.getTime();
		model.addAttribute("tomorrow", DateUtils.formatDate(tomorrow, "yyyy-MM-dd"));
		
		if (tSchedef.getDateissued() == null){
			tSchedef.setDateissued(tomorrow);
			ca.add(Calendar.MONTH, 3);
			tSchedef.setStopdate(ca.getTime());
		}
			
		// 查询所有站点
		model.addAttribute("tSitedList", tSitedtlservice.findListAll());

		model.addAttribute("board", tSchedef.gettSchedefBoardList());
		model.addAttribute("boardnum", tSchedef.gettSchedefBoardList().size());
		model.addAttribute("off", tSchedef.gettSchedefOffList());
		model.addAttribute("offnum", tSchedef.gettSchedefOffList().size());
		model.addAttribute("veh", tSchedef.getTSchedefVehiList());

		// 获取发车日期类型 进行切割
		String str = tSchedef.getDeparttype();
		if (str != null) {
			String[] strs = str.split("_");
			for (int i = 0; i < strs.length; i++) {
				model.addAttribute("departtypes1", strs[0]);
				model.addAttribute("departtypes2", strs[1]);
				model.addAttribute("departtypes3", strs[2]);
				model.addAttribute("departtypes4", strs[3]);
				model.addAttribute("departtypes5", strs[4]);
				model.addAttribute("departtypes6", strs[5]);
				model.addAttribute("departtypes7", strs[6]);
				model.addAttribute("departtypes8", strs[7]);
			}
		}

		// 查出所有客运公司 客运公司需要动态取
		
//		List<Map<String, Object>> mapList = Lists.newArrayList();
//		List<Office> list = officeService.findListByAreaid(Office.FLAT_TYPE_BUS, UserUtils.getUser().getOffice().getArea().getId());
//		for (int i = 0; i < list.size(); i++) {
//			Office e = list.get(i);
//			Map<String, Object> map = Maps.newHashMap();
//			map.put("id", e.getId());
//			map.put("pId", e.getParentId());
//			map.put("pIds", e.getParentIds());
//			map.put("name", e.getName());
//			mapList.add(map);
//		}
//		model.addAttribute("officelist", mapList);
		
		model.addAttribute("updateorview", updateorview);
		
		//如果是updateorview 为调度 或者 调度详情，则转向班次调度界面
		if (updateorview != null && (updateorview.equals("M") || updateorview.equals("D"))){
			if (tSchedef.getStartDate() == null || tSchedef.getStartDate().equals("")){
				tSchedef.setStartDate(DateUtils.formatDate(tomorrow, "yyyy-MM-dd"));
			}
			if (tSchedef.getEndDate() == null || tSchedef.getEndDate().equals("")){
				tSchedef.setEndDate(DateUtils.formatDate(tomorrow, "yyyy-MM-dd"));
			}
			model.addAttribute("tSchedef", tSchedef);
			return "modules/schedef/tSchedefModifyForm";
		}else {
			model.addAttribute("tSchedef", tSchedef);
			return "modules/schedef/tSchedefForm";
		}		
	}

	@RequiresPermissions("schedef:tSchedef:edit")
	@RequestMapping(value = "save")
	public String save(TSchedef tSchedef, Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request) {
		String updateorview = new String("");
		if (!beanValidator(model, tSchedef)) {
			return form(tSchedef, updateorview, model);
		}

		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddhhmm");
		Date date = new Date();

		tSchedef.setSchecode(formatter.format(date));
		tSchedef.setOfficeid(UserUtils.getUser().getOffice().getId());
		tSchedef.setCompanyid(UserUtils.getUser().getCompany().getId());
		// 设置操作人为当前登录用户
		tSchedef.setCreateby(UserUtils.getUser().getId());


		tSchedefService.save(tSchedef);
		/*
		 * TSchedefDrvs drvs = new TSchedefDrvs();
		 * drvs.setDefvehiid(tSchedef.getId()); drvs.setDefdrvid(defdrvid);
		 */
		addMessage(redirectAttributes, "保存班次成功");
		return "redirect:" + Global.getAdminPath() + "/schedef/tSchedef/?repage";
	}
	
	@RequiresPermissions("schedef:tSchedef:edit")
	@RequestMapping(value = "dispatch")
	public String dispatch(TSchedef tSchedef, Model model, RedirectAttributes redirectAttributes,
			HttpServletRequest request) {	
		//后台验证
		String updateorview = new String("M");
		if (!beanValidator(model, tSchedef)) {
			return form(tSchedef, updateorview, model);
		}
		
		// 设置操作人为当前登录用户
		tSchedef.setOfficeid(UserUtils.getUser().getOffice().getId());
		tSchedef.setCompanyid(UserUtils.getUser().getCompany().getId());
		tSchedef.setCreateby(UserUtils.getUser().getId());

		tSchedefService.dispatch(tSchedef);

		addMessage(redirectAttributes, "调度成功!");
		return "redirect:" + Global.getAdminPath() + "/schedef/tSchedefModify/?repage";
	}

	@RequiresPermissions("schedef:tSchedef:edit")
	@RequestMapping(value = "delete")
	public String delete(TSchedef tSchedef, RedirectAttributes redirectAttributes) {
		tSchedefService.delete(tSchedef);
		addMessage(redirectAttributes, "删除班次成功");
		return "redirect:" + Global.getAdminPath() + "/schedef/tSchedef/?repage";
	}

	@RequiresPermissions("schedef:tSchedef:edit")
	@RequestMapping(value = "enableSche")
	public String enableSche(TSchedef tSchedef, RedirectAttributes redirectAttributes) {
		tSchedef.setAuditstatus("1");
		tSchedefService.update(tSchedef);
		addMessage(redirectAttributes, "启用班次成功");
		return "redirect:" + Global.getAdminPath() + "/schedef/tSchedef/?repage";
	}

	@RequiresPermissions("schedef:tSchedef:edit")
	@RequestMapping(value = "disableSche")
	public String disableSche(TSchedef tSchedef, RedirectAttributes redirectAttributes) {
		tSchedef.setAuditstatus("9");
		tSchedefService.update(tSchedef);
		addMessage(redirectAttributes, "停用班次成功");
		return "redirect:" + Global.getAdminPath() + "/schedef/tSchedef/?repage";
	}

	/**
	 * 验证班次名称是否唯一
	 * 
	 * @param oldSchename
	 * @param schename
	 * @return
	 */
	@ResponseBody
	@RequiresPermissions("schedef:tSchedef:edit")
	@RequestMapping(value = "checkSchename")
	public String checkSchename(String oldSchename, String schename) {

		if (schename != null && schename.equals(oldSchename)) {
			return "true";
		} else if (schename != null && tSchedefService.getSchedefBySchename(schename) == null) {
			return "true";
		}
		return "false";
	}

}
